package org.example.config;

import jakarta.annotation.Resource;
import org.example.exception.LoginFailException;
import org.example.exception.LoginSuccessHandler;
import org.example.exception.NotAccessException;
import org.example.exception.NotLoginException;
import org.example.filter.IsLoginSecurityFilter;
import org.example.filter.TokenLoginFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Auther:Liu
 * @Testname:SpringSecurityConfig
 * @Date:2025/9/16 21:43
 */
@EnableWebSecurity
@Configuration
public class SpringSecurityConfig {
    @Resource
    private LoginFailException loginFailException;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private NotAccessException notAccessException;
    @Resource
    private NotLoginException notLoginException;
    @Resource
    private IsLoginSecurityFilter isLoginSecurityFilter;
    @Resource
    private AuthenticationConfiguration config;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(
            AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }
//    @Bean
//    public UserDetailsService userDetailsService() {
//        UserDetails userDetails =
//                User.withUsername("admin")
//                        .password(passwordEncoder().encode("123456"))
//                        .roles("admin")
//                        .build();
//        return new InMemoryUserDetailsManager(userDetails);
//    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin((formLogin) -> formLogin
                //指定自定义登录页面地址
                .loginPage("/login.html")
                //登录访问路径：前台界面提交表单之后跳转到这个路径进行UserDetailsService的验证，必须和表单提交接口一样
                .loginProcessingUrl("/user/login")
                //认证成功之后跳转的路径
                .defaultSuccessUrl("/index.html")
//                .successHandler(loginSuccessHandler).
//                failureHandler(loginFailException)
        );

        //对请求进行访问控制设置
        http.authorizeHttpRequests((a) -> a
                //设置哪些路径可以直接访问，不需要认证
                .requestMatchers("/login.html", "/user/login").permitAll()
                .requestMatchers("/first/a", "/first/b").hasAnyAuthority("manager01", "manager02")
                .requestMatchers("/second/a", "/first/b").hasRole("role01")
                .requestMatchers("/second/b", "/second/c").hasRole("role02")
                .requestMatchers("/first/c").hasAuthority("manager01")
                //其他路径的请求都需要认证
                .anyRequest().authenticated()
        );

//        http.exceptionHandling().accessDeniedPage("/403.html");
        //关闭跨站点请求伪造csrf防护
        http.csrf(AbstractHttpConfigurer::disable);
        // 配置没有登陆和未授权handler
//        http.exceptionHandling((e) ->
//                e.authenticationEntryPoint(notLoginException)
//                        .accessDeniedHandler(notAccessException));
        // 配置过滤器
        http.addFilterBefore(isLoginSecurityFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilter(new TokenLoginFilter(authenticationManager(config)));
        // 配置没有登陆和未授权handler
//        http.exceptionHandling((e) ->
//                e.authenticationEntryPoint(notLoginException)
//                        .accessDeniedHandler(notAccessException));


        return http.build();
    }
}
